package cn.jtcoding.common.framework.utils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Stream;

/**
 * @author jason.tang
 * @date 2021/3/8 17:01
 * @desc
 */

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ReflectUtils {
    private static final String JAVAP = "java.";
    private static final String JAVADATESTR = "java.util.Date";
    private static final String DATEFORMATSTR = "yyyy-MM-dd HH:mm:ss";

    /**
     * 缓存class
     */
    private static final Map<String, Class<?>> CLASS_POOL = Maps.newConcurrentMap();

    /**
     * 缓存method
     */
    private static final Map<String, Method> METHOD_POOL = Maps.newConcurrentMap();

    /**
     * 缓存类型
     */
    private static final Map<String, Class<?>> PRIMITIVE_TYPES = Maps.newHashMap();

    /**
     * 加载一个class
     *
     * @param className
     * @return
     */
    public static Class<?> from(String className) {
        try {
            if (CLASS_POOL.containsKey(className)) {
                return CLASS_POOL.get(className);
            }
            Class<?> clzzz = Class.forName(className);
            CLASS_POOL.put(className, clzzz);
            return clzzz;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 查找一个method
     *
     * @param type
     * @param methodName
     * @return
     */
    public static Method method(Class<?> type, String methodName) {
        String key = type.getName() + ":" + methodName;
        if (METHOD_POOL.containsKey(key)) {
            return METHOD_POOL.get(key);
        }
        Method[] methods = type.getMethods();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                METHOD_POOL.put(key, method);
                return method;
            }
        }
        return null;
    }

    /**
     * 根据类型获取method
     *
     * @param type
     * @param methodName
     * @param paramTypes
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static Method method(Class<?> type, String methodName, Class[] paramTypes) {
        try {
            String key = type.getName() + ":" + methodName + ":" + Arrays.toString(paramTypes);
            if (METHOD_POOL.containsKey(key)) {
                return METHOD_POOL.get(key);
            }
            Method method = type.getMethod(methodName, paramTypes);
            METHOD_POOL.put(key, method);
            return method;
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * 获取Method的形参名称列表
     *
     * @param method
     *            需要解析的方法
     * @return 形参名称列表, 如果没有调试信息, 将返回null
     */
    public static List<String> getParamNames(Method method) {
        try {
            int size = method.getParameterTypes().length;
            if (size == 0) {
                return Lists.newArrayList();
            }
            List<String> list = getParamNames(method.getDeclaringClass()).get(getKey(method));
            if (list != null && list.size() != size) {
                return list.subList(0, size);
            }
            return list;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取Constructor的形参名称列表
     *
     * @param constructor
     *            需要解析的构造函数
     * @return 形参名称列表, 如果没有调试信息, 将返回null
     */
    public static List<String> getParamNames(Constructor<?> constructor) {
        try {
            int size = constructor.getParameterTypes().length;
            if (size == 0) {
                return Lists.newArrayList();
            }
            List<String> list = getParamNames(constructor.getDeclaringClass()).get(getKey(constructor));
            if (list != null && list.size() != size) {
                return list.subList(0, size);
            }
            return list;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    // ---------------------------------------------------------------------------------------------------

    /**
     * 获取一个类的所有方法/构造方法的形参名称Map
     *
     * @param klass
     *            需要解析的类
     * @return 所有方法/构造方法的形参名称Map
     * @throws IOException
     *
     */
    public static Map<String, List<String>> getParamNames(Class<?> klass) throws IOException {
        InputStream in = klass.getResourceAsStream("/" + klass.getName().replace('.', '/') + ".class");
        return getParamNames(in);
    }

    public static Map<String, List<String>> getParamNames(InputStream in) throws IOException {
        DataInputStream dis = new DataInputStream(new BufferedInputStream(in));
        Map<String, List<String>> names = new HashMap<String, List<String>>();
        Map<Integer, String> strs = new HashMap<Integer, String>();
        dis.skipBytes(4);// Magic
        dis.skipBytes(2);// 副版本号
        dis.skipBytes(2);// 主版本号

        // 读取常量池
        int constant_pool_count = dis.readUnsignedShort();
        for (int i = 0; i < (constant_pool_count - 1); i++) {
            byte flag = dis.readByte();
            switch (flag) {
                case 7:// CONSTANT_Class:
                    dis.skipBytes(2);
                    break;
                case 9:// CONSTANT_Fieldref:
                case 10:// CONSTANT_Methodref:
                case 11:// CONSTANT_InterfaceMethodref:
                    dis.skipBytes(2);
                    dis.skipBytes(2);
                    break;
                case 8:// CONSTANT_String:
                    dis.skipBytes(2);
                    break;
                case 3:// CONSTANT_Integer:
                case 4:// CONSTANT_Float:
                    dis.skipBytes(4);
                    break;
                case 5:// CONSTANT_Long:
                case 6:// CONSTANT_Double:
                    dis.skipBytes(8);
                    i++;// 必须跳过一个,这是class文件设计的一个缺陷,历史遗留问题
                    break;
                case 12:// CONSTANT_NameAndType:
                    dis.skipBytes(2);
                    dis.skipBytes(2);
                    break;
                case 1:// CONSTANT_Utf8:
                    int len = dis.readUnsignedShort();
                    byte[] data = new byte[len];
                    dis.read(data);
                    strs.put(i + 1, new String(data, "UTF-8"));// 必然是UTF8的
                    break;
                case 15:// CONSTANT_MethodHandle:
                    dis.skipBytes(1);
                    dis.skipBytes(2);
                    break;
                case 16:// CONSTANT_MethodType:
                    dis.skipBytes(2);
                    break;
                case 18:// CONSTANT_InvokeDynamic:
                    dis.skipBytes(2);
                    dis.skipBytes(2);
                    break;
                default:
                    throw new RuntimeException("Impossible!! flag=" + flag);
            }
        }

        dis.skipBytes(2);// 版本控制符
        dis.skipBytes(2);// 类名
        dis.skipBytes(2);// 超类

        // 跳过接口定义
        int interfaces_count = dis.readUnsignedShort();
        dis.skipBytes(2 * interfaces_count);// 每个接口数据,是2个字节

        // 跳过字段定义
        int fields_count = dis.readUnsignedShort();
        for (int i = 0; i < fields_count; i++) {
            dis.skipBytes(2);
            dis.skipBytes(2);
            dis.skipBytes(2);
            int attributes_count = dis.readUnsignedShort();
            for (int j = 0; j < attributes_count; j++) {
                dis.skipBytes(2);// 跳过访问控制符
                int attribute_length = dis.readInt();
                dis.skipBytes(attribute_length);
            }
        }

        // 开始读取方法
        int methods_count = dis.readUnsignedShort();
        for (int i = 0; i < methods_count; i++) {
            dis.skipBytes(2); // 跳过访问控制符
            String methodName = strs.get(dis.readUnsignedShort());
            String descriptor = strs.get(dis.readUnsignedShort());
            short attributes_count = dis.readShort();
            for (int j = 0; j < attributes_count; j++) {
                String attrName = strs.get(dis.readUnsignedShort());
                int attribute_length = dis.readInt();
                if ("Code".equals(attrName)) { // 形参只在Code属性中
                    dis.skipBytes(2);
                    dis.skipBytes(2);
                    int code_len = dis.readInt();
                    dis.skipBytes(code_len); // 跳过具体代码
                    int exception_table_length = dis.readUnsignedShort();
                    dis.skipBytes(8 * exception_table_length); // 跳过异常表

                    int code_attributes_count = dis.readUnsignedShort();
                    for (int k = 0; k < code_attributes_count; k++) {
                        int str_index = dis.readUnsignedShort();
                        String codeAttrName = strs.get(str_index);
                        int code_attribute_length = dis.readInt();
                        if ("LocalVariableTable".equals(codeAttrName)) {// 形参在LocalVariableTable属性中
                            int local_variable_table_length = dis.readUnsignedShort();
                            List<String> varNames = new ArrayList<String>(local_variable_table_length);
                            for (int l = 0; l < local_variable_table_length; l++) {
                                dis.skipBytes(2);
                                dis.skipBytes(2);
                                String varName = strs.get(dis.readUnsignedShort());
                                dis.skipBytes(2);
                                dis.skipBytes(2);
                                if (!"this".equals(varName)) { // 非静态方法,第一个参数是this
                                    varNames.add(varName);
                                }
                            }
                            names.put(methodName + "," + descriptor, varNames);
                        } else {
                            dis.skipBytes(code_attribute_length);
                        }
                    }
                } else {
                    dis.skipBytes(attribute_length);
                }
            }
        }
        dis.close();
        return names;
    }

    /**
     * 传入Method或Constructor,获取getParamNames方法返回的Map所对应的key
     */
    public static String getKey(Object obj) {
        StringBuilder sb = new StringBuilder();
        if (obj instanceof Method) {
            sb.append(((Method) obj).getName()).append(',');
            getDescriptor(sb, (Method) obj);
        } else if (obj instanceof Constructor) {
            sb.append("<init>,"); // 只有非静态构造方法才能用有方法参数的,而且通过反射API拿不到静态构造方法
            getDescriptor(sb, (Constructor<?>) obj);
        } else
            throw new RuntimeException("Not Method or Constructor!");
        return sb.toString();
    }

    public static void getDescriptor(StringBuilder sb, Method method) {
        sb.append('(');
        for (Class<?> klass : method.getParameterTypes()) {
            getDescriptor(sb, klass);
        }
        sb.append(')');
        getDescriptor(sb, method.getReturnType());
    }

    public static void getDescriptor(StringBuilder sb, Constructor<?> constructor) {
        sb.append('(');
        for (Class<?> klass : constructor.getParameterTypes()) {
            getDescriptor(sb, klass);
        }
        sb.append(')');
        sb.append('V');
    }

    /**
     * 本方法来源于ow2的asm库的Type类
     */
    public static void getDescriptor(final StringBuilder buf, final Class<?> c) {
        Class<?> d = c;
        while (true) {
            if (d.isPrimitive()) {
                char car;
                if (d == Integer.TYPE) {
                    car = 'I';
                } else if (d == Void.TYPE) {
                    car = 'V';
                } else if (d == Boolean.TYPE) {
                    car = 'Z';
                } else if (d == Byte.TYPE) {
                    car = 'B';
                } else if (d == Character.TYPE) {
                    car = 'C';
                } else if (d == Short.TYPE) {
                    car = 'S';
                } else if (d == Double.TYPE) {
                    car = 'D';
                } else if (d == Float.TYPE) {
                    car = 'F';
                } else /* if (d == Long.TYPE) */ {
                    car = 'J';
                }
                buf.append(car);
                return;
            } else if (d.isArray()) {
                buf.append('[');
                d = d.getComponentType();
            } else {
                buf.append('L');
                String name = d.getName();
                int len = name.length();
                for (int i = 0; i < len; ++i) {
                    char car = name.charAt(i);
                    buf.append(car == '.' ? '/' : car);
                }
                buf.append(';');
                return;
            }
        }
    }

    public static <T> T newInstance(Class<T> paramType) {
        try {
            return paramType.newInstance();
        } catch (Exception e) {
            return null;
        }
    }

    static {
        PRIMITIVE_TYPES.put("int", int.class);
        PRIMITIVE_TYPES.put("boolean", boolean.class);
        PRIMITIVE_TYPES.put("char", char.class);
        PRIMITIVE_TYPES.put("byte", byte.class);
        PRIMITIVE_TYPES.put("short", short.class);
        PRIMITIVE_TYPES.put("long", long.class);
        PRIMITIVE_TYPES.put("float", float.class);
        PRIMITIVE_TYPES.put("double", double.class);
    }

    /**
     * 获取基本类型
     *
     * @param primitive
     * @return
     */
    public static Class<?> getBasicType(String primitive) {
        return PRIMITIVE_TYPES.get(primitive);
    }

    /**
     * 判断是否是基本类型
     *
     * @param primitive
     * @return
     */
    public static boolean isBasic(String primitive) {
        return PRIMITIVE_TYPES.containsKey(primitive);
    }

    /**
     * 根据type获取基本类型的class
     *
     * @param type
     * @return
     */
    public static Class<?> getClassType(String type) {
        if (isBasic(type)) {
            return getBasicType(type);
        }
        return from(type);
    }

    /**
     * 根据类名创建一个无参构造函数的对象
     *
     * @param className
     *            类名
     * @param type
     *            Java类型
     * @param <T>
     * @return
     */
    public static <T> T newInstance(String className, Class<T> type) {
        try {
            Object obj = newInstance(Class.forName(className));
            if (null != obj) {
                return type.cast(obj);
            }
        } catch (Exception e) {
        }
        return null;
    }

    public static <T> Constructor<T> getConstructor(Class<T> type, Class<?>... parameterTypes) {
        try {
            Constructor<T> constructor = type.getConstructor(parameterTypes);
            return constructor;
        } catch (Exception e) {
        }
        return null;
    }

    public static boolean hasInterface(Class<?> cls, Class<?> inter) {
        Class<?>[] inters = cls.getInterfaces();
        return Stream.of(inters).filter(interfaceType -> interfaceType.equals(inter)).count() > 0;
    }

    /**
     * 利用反射对Map进行解析并且转换相应Class的对象
     * @param <T>
     *
     * @param map
     * @param clazz
     * @return
     * @throws Exception
     */
    public static <T> T mapToObject(Map<String, Object> map, Class<T> clazz) {
        if (map == null) {
            return null;
        }
        T t = null;
        try {
            t = clazz.newInstance();
            t = mapToSuperObject(map, t);
            Field[] fields = t.getClass().getDeclaredFields();
            for (Field field : fields) {
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }
                Object obj = map.get(field.getName());
                setField(t, field, obj);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return t;
    }

    private static <T> Class<?> setField(T t, Field field, Object obj) throws IllegalAccessException {
        Class<?> typeClazz = field.getType();
        if (obj == null) {
            return typeClazz;
        }
        field.setAccessible(true);
        if (obj.getClass() == typeClazz) {
            field.set(t, obj);
            return typeClazz;
        }
        if (typeClazz == Long.class || typeClazz == long.class) {
            field.set(t, Long.parseLong(String.valueOf(obj)));
        }
        if (typeClazz == Integer.class || typeClazz == int.class) {
            field.set(t, Integer.parseInt(String.valueOf(obj)));
        }
        if (typeClazz == Double.class || typeClazz == double.class) {
            field.set(t, Double.parseDouble(String.valueOf(obj)));
        }
        if (typeClazz == Float.class || typeClazz == float.class) {
            field.set(t, Float.parseFloat(String.valueOf(obj)));
        }
        if (typeClazz == Boolean.class || typeClazz == boolean.class) {
            field.set(t, Boolean.parseBoolean(String.valueOf(obj)));
        }
        if (typeClazz == Locale.class) {
            LocalDate localDate = LocalDate.parse(String.valueOf(obj), DateTimeFormatter.ISO_DATE);
            field.set(t, localDate);
        }
        return typeClazz;
    }

    private static <T> T mapToSuperObject(Map<String, Object> map, T t) {
        if (map == null) {
            return null;
        }
        try {
            Field[] fields = t.getClass().getSuperclass().getDeclaredFields();
            for (Field field : fields) {
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }
                Object obj = map.get(field.getName());
                setField(t, field, obj);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return t;
    }

    /**
     * 利用反射对Object进行解析并且转换成Map键值对的形式
     *
     * @param obj
     * @param excludeFields
     * @return
     */
    public static Map<String, Object> objectToMap(Object obj, String... excludeFields) {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = null;
        List<String> excludeFieldList = null;
        try {
            map = new LinkedHashMap<>();
            if (excludeFields.length != 0) {
                excludeFieldList = Arrays.asList(excludeFields);
            }
            Field[] declaredFields = obj.getClass().getDeclaredFields();
            for (Field field : declaredFields) {
                String fieldName = field.getName();
                // 判断是不是需要跳过某个属性
                if (excludeFieldList != null && excludeFieldList.contains(fieldName)) {
                    continue;
                }
                field.setAccessible(true);
                map.put(field.getName(), field.get(obj));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return map;
    }

    /**
     * 通过递归调用对Object进行解析并且转换成字符Map键值对的形式
     *
     * @param dateFormatStr
     *            格式化时间Date字符串默认<strong>YYYY-MM-dd HH:mm:ss</strong>
     * @param obj
     *            对象
     * @param excludeFields
     *            排除的属性
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, String> objectToMapString(String dateFormatStr, Object obj, String... excludeFields) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            if (excludeFields.length != 0) {
                List<String> list = Arrays.asList(excludeFields);
                objectTransfer(dateFormatStr, obj, map, list);
            } else {
                objectTransfer(dateFormatStr, obj, map, null);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return map;
    }

    /**
     *
     * @param obj
     *            对象
     * @param map
     *            map
     * @param excludeFields
     *            需要排除的对应参数
     * @return
     * @throws IllegalAccessException
     */
    private static Map<String, String> objectTransfer(String dateFormatStr, Object obj, Map<String, String> map,
                                                      List<String> excludeFields) throws IllegalAccessException {
        // 默认字符串
        String formatStr = DATEFORMATSTR;
        // 设置格式化字符串
        if (dateFormatStr != null && !dateFormatStr.isEmpty()) {
            formatStr = dateFormatStr;
        }
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            // String fieldName = clazz.getSimpleName() + "." + field.getName();
            String fieldName = field.getName();
            // 判断是不是需要跳过某个属性
            if (excludeFields != null && excludeFields.contains(fieldName)) {
                continue;
            }
            field.setAccessible(true);
            Object value = field.get(obj);
            if (value == null) {
                map.put(fieldName, null);
                continue;
            }
            Class<?> valueClass = value.getClass();
            if (valueClass.isPrimitive()) {
                map.put(fieldName, value.toString());
            } else if (valueClass.getName().contains(JAVAP)) {// 判断是不是基本类型
                if (valueClass.getName().equals(JAVADATESTR)) {
                    // 格式化Date类型
                    SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
                    Date date = (Date) value;
                    String dataStr = sdf.format(date);
                    map.put(fieldName, dataStr);
                } else {
                    map.put(fieldName, value.toString());
                }
            } else {
                objectTransfer(dateFormatStr, value, map, excludeFields);
            }
        }
        return map;
    }

    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
}
